package web.userUI;

import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import ejb.dto.FlightDTO;

@FacesConverter(value = "flightConverter")
public class FlightConverter implements Converter {

    private static Map<FlightDTO, String> entities = new WeakHashMap<FlightDTO, String>();

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object obj) {
        FlightDTO entity = (FlightDTO) obj; 
        //System.out.println("getAsString: " + entity.getDepartureInfo() + entity.getId());
    	synchronized (entities) {
            if (!entities.containsKey(entity)) {
                entities.put(entity, String.valueOf(entity.getId()));
                return String.valueOf(entity.getId());
            } else {
                return entities.get(entity);
            }
        }
        
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
        for (Entry<FlightDTO, String> entry : entities.entrySet()) {
            if (entry.getValue().equals(uuid)) {
            	//System.out.println("getAsObject: " + entry.getKey().getDepartureInfo());
                return entry.getKey();
            }
        }
        return null;
    }

}